<template>
  <el-card>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <div class="forms">
        <el-form-item label="商品分类" prop="goodsCategoryId">
          <el-cascader
            v-model="ruleForm.goodsCategoryId"
            style="width: 400px"
            :props="props"
            @change="changeCas"
            placeholder="请输入商品分类"
          />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="ruleForm.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品简介">
          <el-input
            v-model="ruleForm.goodsIntro"
            :rows="2"
            type="textarea"
            placeholder="请输入商品简介"
          />
        </el-form-item>
        <el-form-item label="商品价格" prop="originalPrice">
          <el-input
            type="number"
            v-model="ruleForm.originalPrice"
            placeholder="请输入商品价格"
          />
        </el-form-item>
        <el-form-item label="商品售卖价" prop="sellingPrice">
          <el-input
            type="number"
            v-model="ruleForm.sellingPrice"
            placeholder="请输入商品售卖价"
          />
        </el-form-item>
        <el-form-item label="商品库存" prop="stockNum">
          <el-input
            type="number"
            v-model="ruleForm.stockNum"
            placeholder="请输入商品库存"
          />
        </el-form-item>
        <el-form-item label="商品标签" prop="tag">
          <el-input v-model="ruleForm.tag" placeholder="请输入商品标签" />
        </el-form-item>
      </div>
      <el-form-item label="上架状态">
        <el-radio-group v-model="ruleForm.goodsSellStatus" class="ml-4">
          <el-radio label="0" size="large">上架</el-radio>
          <el-radio label="1" size="large">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品主图" prop="goodsName">
        <upLoadImage @getImage="getImage"></upLoadImage>
      </el-form-item>
      <el-form-item label="详细内容">
        <Editor
          style="width: 100%"
          @update:editorValue="update"
          ref="editorRef"
          v-model="ruleForm.goodsDetailContent"
        ></Editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          立即创建
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { api } from "../../../api/api";
import type { categoriesParams } from "../../../types/type";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import "element-plus/es/components/message/style/css";
import upLoadImage from "../../../components/uploadImage.vue";
import Editor from "../../../components/Editor/index.vue";
const route = useRoute();
const router = useRouter();
const editorRef = ref<any>();
onMounted(() => {
  if (route.query.id) {
    api
      .editProductCallbackApi({ id: route.query.id as string })
      .then((res: any) => {
        editorRef.value.valueHtml = res.data.goods.goodsDetailContent;
      });
  }
});
// 表单数据类型约束
interface RuleForm {
  goodsCategoryId: number | number[];
  goodsName: string;
  goodsIntro: string;
  goodsSellStatus: string;
  originalPrice: string;
  sellingPrice: string;
  stockNum: string;
  tag: string;
  goodsDetailContent: string;
  goodsCoverImg: string;
}
// 表单数据
const formSize = ref("large");
const radio1 = ref("0");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  goodsCategoryId: 0,
  goodsName: "",
  goodsIntro: "",
  goodsSellStatus: "",
  originalPrice: "",
  sellingPrice: "",
  stockNum: "",
  tag: "",
  goodsDetailContent: "",
  goodsCoverImg: "",
});
// 表单规则
const rules = reactive<FormRules<RuleForm>>({
  goodsName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  goodsCategoryId: [
    { required: true, message: "请选择商品分类", trigger: "blur" },
  ],
  originalPrice: [
    { required: true, message: "请输入商品价格", trigger: "blur" },
  ],
  sellingPrice: [
    { required: true, message: "请输入售卖价格", trigger: "blur" },
  ],
  stockNum: [{ required: true, message: "请输入商品库存", trigger: "blur" }],
  goodsCoverImg: [
    { required: true, message: "请选择商品图片", trigger: "blur" },
  ],
});
// 级联选择器数据请求参数
const submitData = reactive<categoriesParams>({
  categoryLevel: "1",
  pageNumber: "1",
  pageSize: "1000",
  parentId: "0",
});
import type { CascaderProps } from "element-plus";
// 商品分类节点数据
const props: CascaderProps = {
  label: "categoryName",
  value: "categoryId",
  lazy: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    switch (level) {
      case 0:
        submitData.categoryLevel = "1";
        break;
      case 1:
        submitData.categoryLevel = "2";
        submitData.parentId = node.value.toString();
        break;
      case 2:
        submitData.categoryLevel = "3";
        submitData.parentId = node.value.toString();
        break;
    }
    api.categoriesApi(submitData).then((res: any) => {
      if (res.resultCode == 200) {
        const data = res.data.list;
        data.forEach((item: any) => {
          item.leaf = level >= 2;
        });

        // 返回节点数据
        resolve(data);
      } else {
        ElMessage.error(res.message);
      }
    });
  },
};
// 商品分类最后一级的id
function changeCas(e: any) {
  ruleForm.goodsCategoryId = e[e.length - 1];
}
// img组件传过来的图片链接
function getImage(val: any) {
  if (route.query.id) {
    console.log(val);
    if (typeof val !== "string") {
      // 商品图片回填
      ruleForm.goodsCoverImg = val.goods.goodsCoverImg;
      // 商品名称
      ruleForm.goodsName = val.goods.goodsName;
      // 商品简介
      ruleForm.goodsIntro = val.goods.goodsIntro;
      // 商品价格
      ruleForm.originalPrice = val.goods.originalPrice;
      // 商品售卖价格
      ruleForm.sellingPrice = val.goods.sellingPrice;
      // 商品库存
      ruleForm.stockNum = val.goods.stockNum;
      // 商品标签
      ruleForm.tag = val.goods.tag;
      // 是否上架
      ruleForm.goodsSellStatus = val.goods.goodsSellStatus.toString();
      // 商品分类
      ruleForm.goodsCategoryId = [
        val.firstCategory.categoryId,
        val.secondCategory.categoryId,
        val.thirdCategory.categoryId,
      ];
    }else ruleForm.goodsCoverImg = val;
  }else ruleForm.goodsCoverImg = val;
  
}
// 富文本编辑器
const update = (value: any) => {
  ruleForm.goodsDetailContent = value;
};

// 添加商品提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (route.query.id) {
        let arr: any = ruleForm.goodsCategoryId;
        ruleForm.goodsCategoryId = arr[arr.length - 1];
      }
      const api1 = route.query.id ? api.editGoodsApi : api.addGoodsApi;
      const params: any = route.query.id
        ? { goodsId: route.query.id, ...ruleForm }
        : ruleForm;
      const title = route.query.id ? "编辑成功" : "添加成功";
      api1(params).then((res: any) => {
        if (res.resultCode == 200) {
          ElMessage.success(title);
          router.push("/good");
        } else {
          ElMessage.error(res.message);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>

<style lang="scss" scoped>
.forms {
  width: 400px;
  .el-input {
    width: 100%;
  }
}
</style>
